<template>
  <div class="maincm">
    <div class="main_spac1" style="padding-bottom: 5px">
      <div class="main_white padding10">
        <div class="mainor_form" style="min-height: 30px">
          <div class="mainor_te box">
            <div class="mainor_tew" v-if="!listLoading && list.length == 0">
              <span>请点击</span>
              <svg-icon icon-class="commodity_right_arrow" />
            </div>
            <el-button
              class="mainor_tea"
              style="margin-left: 10px"
              @click="(addedFormVisible = true), (type = 0)"
              >添加分类</el-button
            >
            <router-link to="/commodity/classification/import"
              ><el-button>导入分类</el-button></router-link
            >
          </div>
        </div>
        <div class="main_tree">
          <h3 class="main_tree_h boxdq">
            <span>分类名称</span>
            <span>管理操作</span>
          </h3>
          <div class="main_tree_b">
            <el-tree
              draggable
              :allow-drop="allowDrop"
              @node-drop="sort"
              :data="list"
              node-key="id"
              ref="tree"
              v-loading="listLoading"
              element-loading-text="加载中"
              default-expand-all
              icon-class="el-icon-arrow-right"
              :default-checked-keys="defaultkeys"
              highlight-current
              :props="defaultProps"
              style="min-height: 560px"
            >
              <span
                class="custom-tree-node on"
                slot-scope="{ node, data }"
                @mouseover="data.show = true"
                @mouseleave="data.show = false"
              >
                <span>
                  <em>
                    <svg-icon
                      icon-class="commodity_up_down_arrow"
                      v-if="node.level == 1"
                    />
                    <svg-icon
                      icon-class="commodity_up_down_arrow"
                      v-if="node.level != 1 && data.show"
                    />
                  </em>
                  {{ node.label }}
                </span>
                <span>
                  <el-link
                    type="warning"
                    @click="
                      (addedFormVisible = true),
                        (type = 1),
                        (info.pid = data.id)
                    "
                    v-if="node.level == 1"
                    >添加子分类</el-link
                  >
                  <el-link
                    v-if="data.company_id > 0 ? true : false"
                    type="primary"
                    @click.stop="
                      (addedFormVisible = true),
                        (type = 2),
                        (id = data.id),
                        (info.title = data.title)
                    "
                    >编辑</el-link
                  >
                  <el-link type="danger" @click="delet(data.id)">删除</el-link>
                </span>
              </span>
            </el-tree>
          </div>
        </div>

        <div class="newConBox_p100 paddingBottom10" id="newConBox">
          <div class="newConBox_h32">
            <div :class="['newConBox ', { on: searchBarFixed }]">
              <el-button type="primary" @click="preservation()" v-repeatClick
                >保存排序</el-button
              >
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      :title="type == 0 ? '添加分类' : type == 1 ? '添加子分类' : '编辑分类'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="close"
      :visible.sync="addedFormVisible"
      class="main_dialog dialog450"
    >
      <el-form
        :inline="false"
        :model="info"
        :rules="rules"
        class="demo-form-inline"
        ref="userListFrom"
        label-width="90px"
      >
        <el-form-item label="分类名称：" prop="title">
          <el-input
            v-model.trim="info.title"
            placeholder="分类名称"
            clearable
            class="wid300"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="(addedFormVisible = false), close()"
          >取 消</el-button
        >
        <el-button type="primary" @click="setupmine" v-repeatClick
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  category_index,
  category_add,
  category_edit,
  category_use,
  category_delete,
  category_deleteBefore,
} from "@/api/commodity/commodityClassification";
import rules from "@/rules/commodity/commodityClassification";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";

export default {
  components: {},
  data() {
    return {
      // 树型tree
      defaultkeys: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
      },
      // 增加和编辑
      info: {
        title: "",
        pid: 0,
      },
      id: "",
      type: 0,
      addedFormVisible: false,
      // 验证
      rules,
      // 列表数据
      list: [],
      listLoading: false,
      // 监听滚动
      searchBarFixed: false,
    };
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 200
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 保存排序
    preservation() {
      let arry = [];
      this.list.map((w) => {
        arry.push({
          id: w.id,
          selfNext: [],
          title: w.title,
          company_id: w.company_id,
        });
        if (w.selfNext.length != 0) {
          this.catNext(w.selfNext, arry, arry[arry.length - 1]);
        }
      });
      let data = Object.assign(
        apiUrl().name,
        {
          category_ids: JSON.stringify(arry),
        }
      );
      category_use(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.category_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    catNext(self, arry, selfNext) {
      self.map((w) => {
        selfNext["selfNext"].push({
          id: w.id,
          selfNext: [],
          title: w.title,
          company_id: w.company_id,
        });
        if (w.selfNext.length != 0) {
          let xh = selfNext["selfNext"][selfNext["selfNext"].length - 1];
          this.catNext(w.selfNext, arry, xh);
        }
      });
    },
    // 拖动
    allowDrop(draggingNode, dropNode, type) {
      // console.log(draggingNode, dropNode, type)
      if (draggingNode.level === dropNode.level) {
        if (draggingNode.parent.id === dropNode.parent.id) {
          // 向上拖拽 || 向下拖拽
          return type === "prev" || type === "next";
        }
      } else {
        // 不同级进行处理
        return false;
      }
    },
    sort(draggingNode, dropNode, type, event) {
      var arry = [];
      if (draggingNode.checked) {
        arry.push(draggingNode.key);
      }
      if (dropNode.checked) {
        arry.push(dropNode.key);
      }
      if (draggingNode.childNodes.length != 0) {
        draggingNode.childNodes.map((e) => {
          if (e.checked) {
            arry.push(e.key);
          }
        });
      }
      if (dropNode.childNodes.length != 0) {
        dropNode.childNodes.map((e) => {
          if (e.checked) {
            arry.push(e.key);
          }
        });
      }
      this.$refs.tree.setCheckedKeys(
        this.$refs.tree.getCheckedKeys().concat(arry)
      );
    },
    // 关闭清空表单
    close() {
      this.info = {
        title: "",
        pid: 0,
      };
      this.$refs["userListFrom"].clearValidate();
    },
    // 判断表格是否有子项，无子项不显示展开按钮
    getRowClass(row) {
      if (row.row.selfNext) {
        if (row.row.selfNext.length === 0) {
          return "row-expand-cover";
        }
      }
    },
    // 删除
    delet(id) {
      let data = Object.assign(
        apiUrl().name,
        { id: id }
      );
      this.$confirm("是否删除分类?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          category_deleteBefore(data).then((res) => {
            if (res.errcode == 0) {
              this.category_delete(id);
            } else {
              let msg = res.errmsg;
              this.$confirm(msg + ", 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "error",
              })
                .then(() => {
                  this.category_delete(id);
                })
                .catch(() => {});
            }
          });
        })
        .catch(() => {});
    },
    //彻底删除
    category_delete(id) {
      let data = Object.assign(
        apiUrl().name,
        { id: id }
      );
      category_delete(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.category_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 列表
    category_index() {
      this.listLoading = true;
      let data = Object.assign(
        apiUrl().name
      );
      category_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          res.data.category.forEach((e) => {
            e.show = false;
            if (e.selfNext.length != 0) {
              e.selfNext.forEach((p) => {
                p.show = false;
              });
            }
          });
          this.list = res.data.category;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 新增保存
    add() {
      let data = Object.assign(
        apiUrl().name,
        this.info
      );
      category_add(data).then((res) => {
        this.addedFormVisible = false;
        if (res.errcode == 0) {
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.category_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 编辑保存
    edit() {
      let data = Object.assign(
        apiUrl().name,
        { id: this.id, title: this.info.title }
      );

      category_edit(data).then((res) => {
        this.addedFormVisible = false;
        if (res.errcode == 0) {
          this.$message({
            message: "编辑成功",
            type: "success",
          });
          this.category_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 确认
    setupmine() {
      this.$refs["userListFrom"].validate((valid) => {
        if (valid) {
          this.type == 2 ? this.edit() : this.add();
        }
      });
    },
  },
  created() {
    // 列表
    this.category_index();
  },
};
</script>
<style lang="scss" scoped>
.maincm {
  .main_tree {
    .main_tree_h {
      span {
        &:last-child {
          margin-right: 40px;
        }
      }
    }
  }
  .newConBox.on {
    margin-left: -10px;
    padding-left: 10px;
  }
}
</style>
